package com.bakend.common.config.security.jwt;


import com.alibaba.fastjson.JSON;
import com.bakend.common.R;
import com.bakend.common.config.security.login.CustomerUserDetailService;
import com.bakend.common.utils.HttpUtils;
import com.bakend.common.utils.JwtUtils;
import com.bakend.modules.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 此过滤器用来解析请求头或请求参数中的token，验证token有效性，有效则构造token放入securitycontext上下文中
 */
@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 登录请求，不处理
        if ("/login".equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
        } else if ("OPTIONS".equals(request.getMethod())) {//跨域预检放行
            response.setStatus(HttpServletResponse.SC_OK);
            filterChain.doFilter(request, response);
        } else {
            String token = getToken(request);
            //检查token是否有效
            if (token!=null&&JwtUtils.verify(token)) {
                Object usercode = JwtUtils.parseTokenGetUserId(token);
                if (usercode != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = userService.loadUserByUserCode((String) usercode);
                    if (userDetails != null) {
                        UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
            //即使token无效也放行，security自带的拦截器在SecurityContextHolder中未找到对应token时会走对应的流程
            filterChain.doFilter(request, response);
        }


    }



    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        return token;
    }
}
